<template>
  <div>
    <van-nav-bar title="登录" fixed :z-index="10"></van-nav-bar>
    <div class="nav-con align-center login-con"
         :style="{'background-image':'url(static/img/login/login_back.png)'}">
      <div class="top-area" >
        <van-image src="static/img/login/login_banner.jpg" height="200px"></van-image>
      </div>
      <!--用户名密码登录-->
      <div v-if="loginWay==1">
        <van-cell-group>
          <!--输入账号-->
          <van-field v-model="idCard"  required clearable label="证件号码"
                     placeholder="" label-align="left" size="large" maxlength="20"
                     @blur ="getUserNameAndPhoneForIdcard"
          ></van-field>
          <!--姓名-->
          <van-field v-model="userName"  required clearable label="姓名"
                     placeholder="" label-align="left" size="large" maxlength="20"></van-field>
          <!--手机号码-->
          <van-field v-model="phone"  required clearable label="手机号码"
                     placeholder="" label-align="left" size="large" maxlength="20"></van-field>

          <!--填写验证码-->
          <van-field v-model="smsCode" clearable label="验证码" placeholder="请输入短信验证码" size="large"
                     maxlength="6" required>
            <van-button slot="button" size="small" plain type="danger" class="send-btn" @click="onSMSSend"
                        :disabled="!isSendSMSEnable">
              {{getSendBtnText}}
            </van-button>
          </van-field>
        </van-cell-group>
        <!--账密登录按钮-->
        <div class="button-con">
          <van-button type="danger" round class="login-btn" :disabled="!canPwdLogin" @click="onLoginClick">登录
          </van-button>
<!--          <van-button type="danger" plain round class="login-btn" @click="loginWay=3-loginWay">短信登录</van-button>-->
        </div>
      </div>
      <!--验证码登陆-->
      <div v-else>
        <van-cell-group>
          <!--输入账号-->
          <van-field v-model="userName" left-icon="static/img/login/login_user.png" required clearable label="手机号"
                     placeholder="请输入手机号(随便填)" label-align="left" size="large" maxlength="11"></van-field>
          <!--填写验证码-->
          <van-field v-model="smsCode" clearable label="验证码" placeholder="请输入短信验证码" size="large"
                     left-icon="envelop-o" maxlength="6" required>
            <van-button slot="button" size="small" plain type="danger" class="send-btn" @click="onSMSSend"
                        :disabled="!isSendSMSEnable">
              {{getSendBtnText}}
            </van-button>
          </van-field>
        </van-cell-group>
        <!--账密登录按钮-->
        <div class="button-con">
          <van-button type="danger" round class="login-btn" :disabled="!canSMSLogin" @click="onSMSLogin">登录
          </van-button>
<!--          <van-button type="danger" plain round class="login-btn" @click="loginWay=3-loginWay">账号登录</van-button>-->
        </div>
      </div>
    </div>
  </div>
</template>


<script>
function getUrlKey(name){//获取url 参数

  return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;

}

function getCodeApi(state){//获取code

  let urlNow=encodeURIComponent(window.location.href);

  let scope='snsapi_base'; //snsapi_userinfo //静默授权 用户无感知

  let appid='wx304b179d66268e6b';
  appid = 'wx8c5a10694bf703f1';
  var num=Math.floor(Math.random()*10000+1);
  let url=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=${state}&no=${num}#wechat_redirect`;
  window.location.replace(url);

}

import { getPhoneCode,getOpenId } from "@/api/login";
import { getUserNameAndPhoneForIdcard,examinerLogin,getDicts } from "@/api/grantexaminer/grantexaminer";
  export default {
    name: "login-page",
    data() {
      return {
        userName: '',
        password: '',
        smsCode: '',
        showPassword: false, //是否显示明文
        loginWay: 1, //1: 账密，2：验证码
        smsCountDown: 0,
        smsCountInterval: null,
        idCard : '',
        rpIdCard : '',
        phone: '',
        grantId: null,
        companyId:null,
        openId: undefined
      };
    },
    computed: {
      isSendSMSEnable() {
        // if(this.phone===null){this.phone = '1'}
        return this.smsCountDown <= 0 && this.phone !=null && this.phone.length > 4;
      },
      getSendBtnText() {
        if (this.smsCountDown > 0) {
          return this.smsCountDown + '秒后发送';
        } else {
          return '发送验证码';
        }
      },
      canSMSLogin() {
        return this.userName.length > 4 && this.phone !=null && this.smsCode.length > 4;
      },
      canPwdLogin() {
        return true;
        // return this.userName.length > 4 && this.password.length > 4;
      },
    },
    mounted() {
    },created() {
      console.log('localStorage.getItem("backflag")',localStorage.getItem("backflag"))
      if(localStorage.getItem("backflag")=='1')
      {
        localStorage.setItem("backflag","")
        this.grantId = localStorage.getItem("grantId")?localStorage.getItem("grantId"):''
        if(this.grantId===''){
          localStorage.setItem("backflag","")
          this.$toast.fail({
            message: '末传入考试信息，无法进行下一步操作',
            forbidClick: true, // 禁用背景点击
            duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
          });
          return;
        }
        this.companyId = localStorage.getItem("companyId")?localStorage.getItem("companyId"):''
        if(this.companyId===''){
            localStorage.setItem("backflag","")
            this.$toast.fail({
            message: '末传入派出单位，无法进行下一步操作',
            forbidClick: true, // 禁用背景点击
            duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
          });
          return;
        }
      }
      else
      {
        let code=getUrlKey("code");
        //如果没有拿到code，则表明不是从微信跳转过来
        console.log('code',code)
        if(code==null)
        {
          console.log('come')
          localStorage.setItem("grantId","");
          localStorage.setItem("companyId","");
          localStorage.setItem("rpIdCard","");
          this.grantId = this.$route.query.grantId ? this.$route.query.grantId : ''
          console.log('this.grantId',this.grantId)
          if(this.grantId===''){
            this.$toast.fail({
              message: '末传入考试信息，无法进行下一步操作',
              forbidClick: true, // 禁用背景点击
              duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
            });
            return;
          }
          this.companyId = this.$route.query.companyId ? this.$route.query.companyId : ''
          console.log('this.companyId',this.companyId)
          if(this.companyId===''){
              this.$toast.fail({
              message: '末传入派出单位，无法进行下一步操作',
              forbidClick: true, // 禁用背景点击
              duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
            });
            return;
          }
          this.rpIdCard = this.$route.query.rpIdCard ? this.$route.query.rpIdCard : ''
          localStorage.setItem("grantId",this.grantId);
          localStorage.setItem("companyId",this.companyId);
          localStorage.setItem("rpIdCard",this.rpIdCard);
        }
        else
        {
          this.grantId = localStorage.getItem("grantId")? localStorage.getItem("grantId") : ''
          if(this.grantId===''){
            this.$toast.fail({
              message: '末传入考试信息，无法进行下一步操作',
              forbidClick: true, // 禁用背景点击
              duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
            });
            return;
          }
          this.companyId = localStorage.getItem("companyId")? localStorage.getItem("companyId") : ''
          if(this.companyId===''){
              this.$toast.fail({
              message: '末传入派出单位，无法进行下一步操作',
              forbidClick: true, // 禁用背景点击
              duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
            });
            return;
          }
        }
        this.weixinLogin();
      }

    },
    beforeDestroy() {
      if (this.smsCountInterval) {
        clearInterval(this.smsCountInterval);
      }
    },
    methods: {
      weixinLogin(){
        let userAgent = this.isAlipayOrWechat();
        if ("wechat" === userAgent) {
          let code=getUrlKey("code");//获取url参数code
          if(code) { //拿到code， code传递给后台接口换取opend
            let that = this;
            if(this.openId===undefined)
            {
              getOpenId(code).then(res=>{
                if(res.code==200){
                  this.openId = res.msg;
                  this.onLoginClick();
                }else{
                }
              }).catch(err=>{
                console.log(err);
              })
            }else {
              this.onLoginClick();
            }
          }else{
            getCodeApi("_wx");
          }
        }
      },
      onSMSSend() {
        getPhoneCode(this.phone).then(res=>{
          console.log(res);
          if(res.code === 200){
          this._showLoading();
          setTimeout(() => {
            this._dismissLoading();
            this._showToast('已发送');
            this.smsCountDown = 60;
            this.startSMSTimer();
          }, 300);}
          else
          {
            this.msgError(res.msg);
          }
        })
      },
      startSMSTimer() {
        this.smsCountInterval = setInterval(() => {
          this.smsCountDown--;
          if (this.smsCountDown <= 0) {
            clearInterval(this.smsCountInterval);
          }
        }, 1000);
      },
      onSMSLogin() {
        this.onLoginClick();
      },
      // 模拟登陆
      onLoginClick() {
        if(this.idCard===undefined || this.idCard===''){
          return;
        }
        if(!this.isValidIDCard(this.idCard))
        {
           this.$toast.fail({
              message: '身份证输入错误，请检查',
              forbidClick: false, // 禁用背景点击
              duration:1000 // 持续时间，默认 2000，0 表示持续展示不关闭
           });
          return;
        }
        // getDicts("technical_title").then(response => {
        //   console.log(response);
        // });
        //登陆
        let param = {}
        param["name"] = this.userName;
        param["idcard"] = this.idCard;
        param["smsCode"] = this.smsCode;
        param["grantId"] = this.grantId;
        param["phone"] = this.phone;
        param["wechatId"] = this.openId;
        examinerLogin(param).then(res => {
          if(res.code==200){
            this.$toast.success("登陆成功");
            res.data.grantId = this.grantId;
            res.data.companyId = this.companyId;
            localStorage.setItem('userInfo', JSON.stringify(res.data));
            // const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            // console.log(userInfo["name"])
            // this._routeReplace('userInfoImg');
            console.log(res.data.grantType);
            this._routeReplace(res.data.grantType);
          }else{
            this.$toast.fail(res.msg);
          }
        }).catch(error=>{
          this.$toast.fail(error.message);
        })
      },
      //保存用户信息
      saveUserInfo() {
        let info = {userName: this.userName};
        // 全局修改
        this.$store.commit('setUserInfo', info);
        // 持久化修改
        localStorage.setItem('userInfo', JSON.stringify(info));
      },
      getUserNameAndPhoneForIdcard(){
        if(!this.isValidIDCard(this.idCard))
        {
           this.$toast.fail({
              message: '身份证输入错误，请检查',
              forbidClick: false, // 禁用背景点击
              duration: 1000 // 持续时间，默认 2000，0 表示持续展示不关闭
           });
          return;
        }
        let param = {}
        param["idcard"] = this.idCard;
        getUserNameAndPhoneForIdcard(param).then(res=>{
          if(res.code===200){
            this.userName = res.data.name;
            this.phone = res.data.phone;
          }
        })
      },
      isValidIDCard(idCard) {
        // 身份证正则表达式
        let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

        let validflag = reg.test(idCard);
        if(validflag)
        {
          if(idCard.length ==18)
          {
            return this.verifyCode(idCard);
          }else
          {
            return validflag
          }
        }else
        {
          return validflag;
        }
      },
      verifyCode(id){
        if(id.length !=18 )
          return false;
        /*1、从第一位到第十七位的系数分别为：
          7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2
          将这17位数字和系数相乘的结果相加。 */
        let arr = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
        let sum = 0;
        for(var i=0; i<arr.length; i++){
          sum += parseInt(id.charAt(i)) * arr[i];
        }
        //2、用加出来和除以11，看余数，
        let c = sum%11;
        //3、分别对应的最后一位身份证的号码为：1－0－X－9－8－7－6－5－4－3－2
        let ch = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        let code = ch[c];
        let last = id.charAt(17);
        last = last=='x' ? 'X': last;
        return last == code;
      },
      isAlipayOrWechat(){
        var userAgent = window.navigator.userAgent.toLowerCase();
        if (userAgent.match(/Alipay/i) == "alipay") {
          //alert("支付宝浏览器");
          return "alipay";

        } else if (userAgent.match(/MicroMessenger/i) == "micromessenger") {
          // alert("微信浏览器");
          return "wechat";
        } else {    return "";  }
      }
    },
  }
</script>

<style scoped>
  .send-btn {
    height: 26px;
    line-height: 24px;
  }

  .button-con {
    margin-top: 36px;
  }

  .top-area {
    margin: 0px 0;
  }

  .login-con {
    background-size: 100% 100%;
    height: calc(100vh - 46px);
  }

  .login-btn {
    width: 60%;
    margin: 12px;
  }

  .top-logo {
    width: 100px;
    margin: 16px 0;
  }
</style>
